package com.ruoyi.web.controller.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WebServerOrder;
import com.ruoyi.system.domain.WebServerUser;
import com.ruoyi.system.domain.WebUser;
import com.ruoyi.system.service.*;
import io.swagger.annotations.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author wsliupan
 * @title: _MallProductController
 * @projectName yuansheng
 * @description: 商城列表
 * @date 2021-6-1422:10
 */
@Api(tags = "门店信息")
@RestController
@RequestMapping("/rest/dept")
public class _DeptController extends BaseController {
    @Autowired
    private ISysDeptService iSysDeptService;
//    @Autowired
//    private ISysConfigService iSysConfigService;
    @Autowired
    private IWebUserService iWebUserService;

    @ApiOperation(value = "门店列表",notes = "按照附近距离排序")
    @GetMapping()
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回成功",response = SysDept.class),
    })
    public AjaxResult listAll(String lat,String lng,Integer pageSize,Integer pageNum,Long userId) {
        SysDept dept = new SysDept();
        dept.setLatitude(lat);
        dept.setLongitude(lng);
        dept.setStatus("0");
        Map<String, Object> map = new HashMap<String, Object>();
        String distance_k= configService.selectConfigByKey("distance_k");
        if(StringUtils.isEmpty(distance_k)){
            distance_k = "100";
        }
        dept.setDistance(Integer.valueOf(distance_k));
        List<Map<String, Object>> maps = null;
        map.put("showPrice", "true");
        Long userDeptId= null;
        if(userId != null){
            int count = iWebServerOrderService.count(new QueryWrapper<WebServerOrder>().eq("user_id",userId));
            if(count > 0)
                map.put("showPrice", "false");

            WebUser user = iWebUserService.getById(userId);
            if(user.getDeptId() != null){
                userDeptId = user.getDeptId();
                Map map_ = new HashMap();
                map_.put("dept_id_map",user.getDeptId());
                dept.setParams(map_);

                dept.setDeptId(user.getDeptId());
                maps = iSysDeptService.selectDistance(dept);
            }

        }

        if(StringUtils.isNotEmpty(dept.getLatitude()) && StringUtils.isNotEmpty(dept.getLongitude())){
            dept.setDeptId(null);
            dept.setDelFlag(userDeptId+""); //临时变量，过滤已绑定的门店
            if(CollectionUtils.isNotEmpty(maps)){
                startPage();
                List<Map<String, Object>> maps2 = iSysDeptService.selectDistance(dept);
                if(CollectionUtils.isNotEmpty(maps2)){
                    for(Map map2 : maps2){
                        maps.add(map2);
                    }
                }
            }else{
                startPage();
                maps = iSysDeptService.selectDistance(dept);
            }

        }else{
//            startPage();
//            maps = iSysDeptService.selectDistanceNoLat(dept);
            return error("未获取到当前位置信息");
        }

        TableDataInfo t = getDataTable(maps);
        map.put("pages", t);

        String show_login= configService.selectConfigByKey("show_login");
        map.put("show_login", show_login);

        //绑定门店
        WebUser webUser = iWebUserService.getById(userId);
        if(webUser != null && webUser.getDeptId() == null && CollectionUtils.isNotEmpty(maps)){
            Map map2 = maps.get(0);
            webUser.setDeptId(Long.valueOf(map2.get("dept_id")+""));
            iWebUserService.saveOrUpdate(webUser);
        }

        return AjaxResult.success(map);
    }

    @ApiOperation(value = "门店详情")
    @GetMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lat", value = "经纬度"),
            @ApiImplicitParam(name = "lng", value = "经纬度"),
            @ApiImplicitParam(name = "deptId", value = "门店ID", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)

    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回成功",response = SysDept.class),
    })
    public AjaxResult detail(Long deptId,String lat,String lng ,Long userId){
        if(deptId == null){
            return error("请传入门店ID");
        }

        SysDept dept = new SysDept();
        dept.setLatitude(lat);
        dept.setLongitude(lng);
        dept.setDeptId(deptId);
        List<Map<String, Object>> maps = iSysDeptService.selectDistance(dept);
        if(CollectionUtils.isEmpty(maps)){
            return error("门店不存在");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("dept",maps.get(0));

        //服务人员
        List<Map<String,Object>> listServerUser = iWebServerUserService.listMaps(new QueryWrapper<WebServerUser>()
                .eq("dept_id",maps.get(0).get("dept_id").toString())
                .eq("status",0).select("realname,id"));
        map.put("listServerUser",listServerUser);

        map.put("showPrice", "true");
        if(userId != null){
            int count = iWebServerOrderService.count(new QueryWrapper<WebServerOrder>().eq("user_id",userId));
            if(count > 0)
                map.put("showPrice", "false");
        }


        return AjaxResult.success(map);
    }

    @ApiOperation(value = "根据日期获取技师")
    @GetMapping("getServerUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preDay", value = "预约日期，2021-06-25", required = true),
            @ApiImplicitParam(name = "deptId", value = "门店ID", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)

    })
    public AjaxResult getServerUser(Long deptId,String preDay ,Long userId){
        if(deptId == null){
            return error("请传入门店ID");
        }
        if(preDay == null){
            return error("请传入预约日期");
        }
        if(userId == null){
            return error("请传入用户ID");
        }
        preDay = preDay.replace("/","-");
        Map<String,Object> map = new HashMap<>();
        //服务人员
        List<Map<String, Object>> listServerUser = getServerUserMaps(deptId, preDay);

        map.put("listServerUser",listServerUser);

        return AjaxResult.success(map);
    }

    private List<Map<String, Object>> getServerUserMaps(Long deptId, String preDay) {
        List<Map<String,Object>> listServerUser = iWebServerUserService.listMaps(new QueryWrapper<WebServerUser>()
                .eq("dept_id", deptId)
                .eq("status",0)
                .select("realname","id"));

        if(CollectionUtils.isNotEmpty(listServerUser)){
            Iterator<Map<String,Object>> iterator = listServerUser.iterator();
            while (iterator.hasNext()){
                Map<String,Object> map = iterator.next();
                map.put("realname",map.get("id")+" "+map.get("realname"));
                int serverUserId = Integer.valueOf(map.get("id")+"");
                List<String> times = iSysDeptService.selectServerUserTime(preDay, deptId,serverUserId , false);
                if(CollectionUtils.isEmpty(times)){
                    iterator.remove();
                }
            }
        }
        return listServerUser;
    }

    /**
     * 查询技师的可用
     * @param preDay
     * @param serverUserId
     * @return
     */
    @ApiOperation(value = "查询技师的可用时间")
    @GetMapping("getUserTime")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preDay", value = "预约日期，2021-06-25", required = true),
            @ApiImplicitParam(name = "serverUserId", value = "技师ID", required = true),
            @ApiImplicitParam(name = "deptId", value = "门店ID", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)

    })
    public AjaxResult getUserTime(String preDay, Integer serverUserId , Long deptId){
        preDay = preDay.replace("/","-");
        return AjaxResult.success(iSysDeptService.selectServerUserTime(preDay,deptId,serverUserId,false));
    }



    @Autowired
    private IWebRecycleTypeService webRecycleTypeService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IWebServerUserService iWebServerUserService;
//    @Autowired
//    private DictService dictService;

    @Autowired
    private IWebServerOrderService iWebServerOrderService;
//    @Autowired
//    private IWebUserService iWebUserService;
}
